package HomeWork;

public class Demo6 {
    private static int j = 0; // 共享变量
    private static final Object lock = new Object(); // 锁对象
    public static void main(String[] args) {
        Thread incrementThread1 = new Thread(new IncrementTask(), "I1");
        Thread incrementThread2 = new Thread(new IncrementTask(), "I2");
        Thread decrementThread1 = new Thread(new DecrementTask(), "D1");
        Thread decrementThread2 = new Thread(new DecrementTask(), "D2");
        incrementThread1.start();
        incrementThread2.start();
        decrementThread1.start();
        decrementThread2.start();
        try {
            incrementThread1.join();
            incrementThread2.join();
            decrementThread1.join();
            decrementThread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("最终 j 的值: " + j);
    }
    static class IncrementTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                synchronized (lock) {
                    j++;
                }
            }
            System.out.println(Thread.currentThread().getName() + " 完成");
        }
    }
    static class DecrementTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                synchronized (lock) {
                    j--;
                }
            }
            System.out.println(Thread.currentThread().getName() + " 完成");
        }
    }
}
